package com.hui.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hui.entity.Menu;
import com.hui.service.MenuService;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Description Menu控制层
 */
@WebServlet(urlPatterns = {"/getAllMenu", "/getChildMenu", "/changeMenuState"})
public class MenuServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        String uri = req.getRequestURI();

        if (uri.endsWith("getAllMenu")) {
            getAllMenu(req, resp);
        } else if (uri.endsWith("getChildMenu")) {
            getChildMenu(req, resp);
        } else if (uri.endsWith("changeMenuState")) {
            changeMenuState(req, resp);
        }

    }

    /**
     * 修改菜单状态
     **/
    private void changeMenuState(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        int menuId = Integer.parseInt(req.getParameter("menuId"));
        String menuState = req.getParameter("menuState");

        MenuService service = new MenuService();
        service.changeMenuState(menuId, menuState);

//        resp.getWriter().write("OK");

    }

    /**
     * 获取二级菜单
     **/
    private void getChildMenu(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String code = req.getParameter("code");

        MenuService service = new MenuService();
        List<Menu> list = service.getChildMenu(code);

        //将list转化为json形式
        ObjectMapper mapper = new ObjectMapper();
        String listJson = mapper.writeValueAsString(list);

        resp.getWriter().write(listJson);

    }

    /**
     * 获取菜单
     **/
    private void getAllMenu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        MenuService service = new MenuService();
        Map<String, List<Menu>> map = service.getAllMenu();

        req.setAttribute("map", map);

        req.getRequestDispatcher("admin_menu_list.jsp").forward(req, resp);

    }
}
